package com.qs.user.pay.util;

import android.util.Log;

import java.security.MessageDigest;
import java.util.Map;
import java.util.Random;

import static com.qs.user.pay.util.MD5.getMessageDigest;

/**
 * Created by Walter on 2019/7/26.
 */

public class GeneralUtils {


    /**
     * 获取json
     * @param names
     * @param strs
     * @return
     */
    public static String getJson(String[] names, String[] strs) {
        StringBuilder result = new StringBuilder("{\"");
        for (int i = 0; i < strs.length; i++) {
            result = result.append(names[i] + "\"");
            result = result.append(":\"");
            result = result.append(strs[i] + "\"");
            if (i < strs.length - 1)
                result = result.append(",\"");
        }
        result = result.append("}");
        return result.toString();
    }

    /**
     * 加密
     * 32位大写加密
     *
     * @param plaintext 明文
     * @return ciphertext 密文
     */
    public final static String toMd5(String plaintext) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = plaintext.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str).toUpperCase();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 得到随机字符串
     */
    public static String genNonceStr() {
        Random random = new Random();
        return getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    /**
     * 得到当前时间戳
     */
    public static long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    public static String getPackageSign(Map<String,String> map){
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String,String> entry :map.entrySet()){
            sb.append(entry.getKey());
            sb.append('=');
            sb.append(entry.getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(WXConstants.API_KEY);
        String packageSign = getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", sb.toString());
        Log.e("orion", packageSign);
        return packageSign;
    }
}
